package com.siwei.mes.controller.experiment;

import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.result.ApiResult;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.validator.AddGroup;
import com.siwei.mes.common.validator.PageGroup;
import com.siwei.mes.common.validator.UpdateGroup;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.entity.vo.CreateMaterialsExperimentVo;
import com.siwei.mes.entity.vo.ExperimentBatchVo;
import com.siwei.mes.entity.vo.ExperimentVo;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.enums.RoleEnum;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.service.experiment.ExperimentWaybillService;
import com.siwei.mes.service.system.AuthService;
import com.siwei.mes.upload.erp.UploadErpService;
import com.siwei.mes.upload.erp.entity.ErpWbcheckinfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账相关
 *
 * @author linzi
 * @since 2023-12-18 22:11:47
 */
@Slf4j
@Api(value = "试验台账")
@RestController
@RequestMapping("experiment")
public class ExperimentController {
    @Resource
    private ExperimentService experimentService;
    @Resource
    private UploadErpService uploadErpService;
    @Resource
    private ExperimentWaybillService experimentWaybillService;
    @Resource
    private AuthService authService;

    @ApiOperation("已读新任务单")
    @PostMapping("/viewNewTask")
    public Json viewNewTask(@RequestBody Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        experimentService.viewNewTask(entity.getId());
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "新增原材料相关试验台账")
    @PostMapping("/createMaterialsExperiment")
    public Json createMaterialsExperiment(@RequestBody @Validated CreateMaterialsExperimentVo createMaterialsExperimentVo) {
        experimentService.createMaterialsExperiment(createMaterialsExperimentVo);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "新增试验台账  混凝土")
    @PostMapping("/create")
    public Json create(@RequestBody @Validated(AddGroup.class) Experiment entity) {
        return Json.succ().data(ApiResult.addColumn("id", experimentService.createConcrete(entity)));
    }

    @ApiOperation(value = "修改试验台账")
    @PostMapping("/update")
    public Json update(@RequestBody @Validated(UpdateGroup.class) Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        experimentService.update(entity);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "作废试验台账")
    @PostMapping("/delete")
    public Json delete(@RequestBody Experiment entity) {
        experimentService.delete(entity.getId());
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "分页获取试验台账")
    @PostMapping("/page")
    public Json appPage(@RequestBody @Validated(PageGroup.class) PageQuery<Experiment, Experiment> query) {
        return Json.succ().data(experimentService.getPage(query));
    }

    @ApiOperation(value = "根据主键id获取试验台账")
    @GetMapping("loadById")
    public Json loadById(@RequestParam("id") Long id) {
        return Json.succ().data(experimentService.loadById(id));
    }

    @ApiOperation(value = "获取所有试验台账")
    @PostMapping("getAll")
    public Json getAll(@RequestBody Experiment entity) {
        return Json.succ().data(ApiResult.addList(experimentService.getAll(entity)));
    }

    @ApiOperation("接收")
    @PostMapping("accept")
    public Json accept(@RequestBody Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        experimentService.accept(entity.getId(), true);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("生成报告 (原材料)")
    @PostMapping("generateReport")
    public Json generateReport(@RequestBody Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        experimentService.generateReport(entity.getId());
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("完成")
    @PostMapping("finish")
    public Json finish(@RequestBody Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        Experiment experiment = experimentService.finish(entity.getId());

        /**不需要是混凝土类型的*/
        if (experiment.getExperimentType().equals(MaterialsEnum.CONCRETE.getCode())) {
            return Json.succ().data(new ApiResult());
        }
        Integer checkType = experiment.getCheckType();//检查类型 1-快检 2-批检
        Integer isQualified = experiment.getIsQualified();//是否合格 1-合格 2-不合格
        String handlingSuggestion = experiment.getHandlingSuggestion();//处理意见
        /**这里发送对应的运单记录通知给ERP*/
        List<Waybill> list = experimentWaybillService.selectByExperimentId(entity.getId());
        for (Waybill waybill : list) {
            ErpWbcheckinfo erpWbcheckinfo = new ErpWbcheckinfo();
            erpWbcheckinfo.setWLID(waybill.getWaybillId());
            if (checkType.equals(CheckEnum.QUICK.getCode())) {
                erpWbcheckinfo.setQuickTestID(experiment.getId());
                erpWbcheckinfo.setQuickTestNo(experiment.getExperimentNo());
                if (isQualified == 1) {
                    erpWbcheckinfo.setQuickTestResult("合格");
                    erpWbcheckinfo.setQuickTestRemark("合格");
                } else if (isQualified == 2) {
                    erpWbcheckinfo.setQuickTestResult("不合格");
                    erpWbcheckinfo.setQuickTestRemark(handlingSuggestion);
                }
            } else if (checkType.equals(CheckEnum.BATCH.getCode())) {
                erpWbcheckinfo.setBatchTestID(experiment.getId());
                erpWbcheckinfo.setBatchTestNo(experiment.getExperimentNo());
                if (isQualified == 1) {
                    erpWbcheckinfo.setBatchTestResult("合格");
                    erpWbcheckinfo.setBatchTestRemark("合格");
                } else if (isQualified == 2) {
                    erpWbcheckinfo.setBatchTestResult("不合格");
                    erpWbcheckinfo.setBatchTestRemark(handlingSuggestion);
                }
            } else {
                log.info("未知类型：" + checkType);
                continue;
            }
            try {
                uploadErpService.uploadWbcheckInfo(erpWbcheckinfo, true);
            } catch (Exception e) {
                log.info("推送到ERP失败，错误信息：【{}】", e.getMessage(), e);
            }
        }
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("拒绝")
    @PostMapping("refuse")
    public Json refuse(@RequestBody Experiment entity) {
        assertTrue(entity.getId() == null, "试验台账id为空");
        experimentService.refuse(entity.getId());
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("getAllCount")
    @PostMapping("getAllCount")
    public Json getAllCount(@RequestBody Experiment entity) {
        return Json.succ().data(ApiResult.addColumn("totalCount", experimentService.getAllCount(entity)));
    }

    @ApiOperation("实验台账绑定小票信息")
    @PostMapping("bindExperimentItemOrder")
    public Json bindExperimentItemOrder(@RequestBody ExperimentVo vo) {
        experimentService.bindExperimentItemOrder(vo);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("实验台账绑定运单信息")
    @PostMapping("bindExperimentWaybill")
    public Json bindExperimentWaybill(@RequestBody ExperimentVo vo) {
        experimentService.saveExperimentWaybill(vo);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("批量修改实验台帐批次")
    @PostMapping("updateBatchByIds")
    public Json updateBatchByIds(@RequestBody ExperimentBatchVo vo) {
        experimentService.updateBatchByIds(vo);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("批量修改实验,根据材料规格和材料名称修改物料名称和物料规格")
    @AnonymousAccess
    @GetMapping("updateBatchExperimentMatter")
    public Json updateBatchExperimentMatter() {
        experimentService.updateBatchExperimentMatter();
        return Json.succ();
    }

    @ApiOperation("批量修改实验,处理历史完成台账报告编号未赋值问题")
    @AnonymousAccess
    @GetMapping("updateBatchExperimentReportNo")
    public Json updateBatchExperimentReportNo() {
        experimentService.updateBatchExperimentReportNo();
        return Json.succ();
    }

    @ApiOperation("批量修改实验,补全是否甲供字段")
    @AnonymousAccess
    @GetMapping("updateBatchExperimentSelfSupply")
    public Json updateBatchExperiment() {
        experimentService.updateBatchExperimentSelfSupply();
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("批量修改实验,补全是否甲供字段")
    @AnonymousAccess
    @PostMapping("updateExperimentSelfSupply")
    public Json updateBatchExperiment(@RequestBody Experiment experiment) {
        experimentService.updateBatchExperiment(experiment);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("保存协会相关信息")
    @PostMapping("submitShxhSynchronizedata")
    public Json submitShxhSynchronizedata(@RequestBody ShxhSynchronizedata entity) {
        assertTrue(entity.getExperimentId() == null, "试验委托id为空");
        assertTrue(StringUtils.isBlank(entity.getConsignId()), "协会委托编号为空");
        assertTrue(StringUtils.isBlank(entity.getSampleId()), "协会样品编号为空");
        List<String> rolePermission = new ArrayList<>();
        rolePermission.add(RoleEnum.TESTER_DIRECTOR.getCode());
        rolePermission.add(RoleEnum.CHIEF_ENGINEER.getCode());
        assertTrue(!rolePermission.contains(authService.getLoginUserRole()), "您暂无权限操作");
        experimentService.submitShxhSynchronizedata(entity);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "撤销上传")
    @GetMapping("revokeUpload")
    public Json revokeUpload(@RequestParam("id") Long id) {
        experimentService.revokeUpload(id);
        return Json.succ().data(new ApiResult());
    }
}
